from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.utils.translation import gettext_lazy as _
from backend.users.models import GroupSetting
from backend.gnsuser.models import GnsUser

from backend.users.forms import UserAdminChangeForm, UserAdminCreationForm

User = get_user_model()

class GnsUserInline(admin.StackedInline):
    model = GnsUser
    can_delete = False
    verbose_name_plural = 'GnsUser'



@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
    form = UserAdminChangeForm
    add_form = UserAdminCreationForm
    fieldsets = (
        (None, {"fields": ("username", "password")}),
        (_("Personal info"), {"fields": ("name", "email")}),
        (
            _("Permissions"),
            {
                "fields": (
                    "is_active",
                    "is_staff",
                    "is_superuser",
                    "groups",
                    "user_permissions",
                ),
            },
        ),
        (_("Important dates"), {"fields": ("last_login", "date_joined")}),
    )
    list_display = ["username",  "is_superuser"]
    search_fields = ["username"]
    inlines = [GnsUserInline]


class GroupSettingInline(admin.StackedInline):
    model = GroupSetting
    
class GroupAdmin(auth_admin.Group):
    inlines = [
        GroupSettingInline,
    ]

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        if db_field.name == "users":
            qs = kwargs.get("queryset", db_field.remote_field.model.objects)
            # Avoid a major performance hit resolving permission names which
            # triggers a content_type load:
            # kwargs["queryset"] = qs.select_related("content_type")
            kwargs["queryset"] = qs

        return super().formfield_for_manytomany(db_field, request=request, **kwargs)



class MyGroupAdmin(auth_admin.GroupAdmin):
    
    # search_fields = ("name",)
    # ordering = ("name",)
    # filter_horizontal = ("permissions",)

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        if db_field.name == "users":
            qs = kwargs.get("queryset", db_field.remote_field.model.objects)
            # Avoid a major performance hit resolving permission names which
            # triggers a content_type load:
            # kwargs["queryset"] = qs.select_related("content_type")
            kwargs["queryset"] = qs

        return super().formfield_for_manytomany(db_field, request=request, **kwargs)
    
admin.site.unregister(Group)
admin.site.register(Group,MyGroupAdmin)
admin.site.register(GroupSetting,GroupSettingInline)
